
const crypto = require('crypto')
const password = "shenshuai"
/**
 * @description: 生成公钥和私钥
 * @param {*}
 * @return {*}
 */
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
    modulusLength: 4096,
    publicKeyEncoding:{
        type: 'spki',
        format: 'pem'
    },
    privateKeyEncoding:{
        type: "pkcs8", //私钥编码格式
        format: 'pem',
        cipher: 'aes-256-cbc',
        passphrase: password
    }
})
console.log(publicKey, privateKey);
/**
 * @description: 使用公钥加密
 * @param {publicKey} 公钥
 * @param {string} 要加密的数据
 * @return {*} 加密后的数据
 */
const encrypt = (publicKey, string)=>{
    return crypto.publicEncrypt({key:publicKey, passphrase: password}, Buffer.from(string)).toString('hex')
}

/**
 * @description: 使用私钥解密
 * @param {privateKey} 私钥
 * @param {encryptedString} 被解密的数据
 * @return {*} 解密后数据
 */
const decrypt = (privateKey, encryptedString) =>{
    return crypto.privateDecrypt({key:privateKey, passphrase: password}, Buffer.from(encryptedString, 'hex'))
}

let data = 'node实现非对称加密，使用rsa算法'
const encryptedString = encrypt(publicKey, data)
console.log(`公钥加密后的结果：${encryptedString}`);
const decryptedString = decrypt(privateKey, encryptedString);
console.log(`私钥解密后的结果：${decryptedString}`);